#pragma once 
#include<iostream>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
using namespace std;

const char *pathname = "/home/jz/workdir/learn/shm_ipc";
const int proj_id = 0x66;

// 在内核中，共享内存的大小是以4KB为基本单位的. 你只能用你申请的大小。建议申请大小是n*4KB
const int defaultsize = 4096; // 单位是字节



key_t GetShmKeyOrDir()
{
    key_t k = ftok(pathname,proj_id);//根据路径和项目id生成一个唯一键值
    if(k < 0)
    {
        std::cerr << "ftok error, errno : " << errno << ", error string: " << strerror(errno) << std::endl;
        exit(1);
    }
    return k;
}
std::string ToHex(key_t k)
{
    char buffer[1024];
    snprintf(buffer,sizeof(buffer),"0x%x",k);
    return buffer;
}




int CreatShmOrDir(key_t key, int size, int flag)
{
    int shmid = shmget(key,size,flag);
    if(shmid < 0)
    {
        std::cerr << "shmget error, errno : " << errno << ", error string: " << strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}
//客户端调用
int GetShm(key_t key, int size)
{
    return CreatShmOrDir(key,size,IPC_CREAT);
}
//服务端调用
int CreatShm(key_t key, int size)
{   
    return CreatShmOrDir(key,size,IPC_CREAT|IPC_EXCL|0666);
}


//连接共享内存和调用进程地址空间
void* ShmAttach(int shmid)
{
    //attaches the System V shared memory segment identified by shmid to the address space of the calling process. 
    void * addr = shmat(shmid,nullptr,0);
    if((long long int)addr == -1)
    {
        std::cerr << "shmat error" << std::endl;
        return nullptr;
    }
    return addr;
}
//拆开共享内存和调用进程内存地址空间
void ShmDatch(void* addr)
{
    //detaches the shared memory segment located at the address specified by shmaddr from the address space of the  calling process.
    int n = shmdt(addr);
    if(n < 0)
    {
        std::cerr<<"shmdt error"<<std::endl;
    }
}

//删除共享内存
void DeleteShm(int shmid)
{
    int n = shmctl(shmid,IPC_RMID,nullptr);
    if(n < 0)
    {
        std::cerr << "shmctl error" << std::endl;
    }
    else 
    {
        std::cout << "shmctl delete shm success, shmid: " << shmid << std::endl;
    }
}

void ShmDebug(int shmid)
{
    struct shmid_ds shmds;
    int n = shmctl(shmid,IPC_STAT, &shmds);
    if(n < 0)
    {
        std::cerr << "shmctl error" << std::endl;
        return;
    }
    std::cout << "shmds.shm_segsz: " << shmds.shm_segsz << std::endl;
    std::cout << "shmds.shm_nattch:" << shmds.shm_nattch << std::endl;
    std::cout << "shmds.shm_ctime:" << shmds.shm_ctime << std::endl;
    std::cout << "shmds.shm_perm.__key:" << ToHex(shmds.shm_perm.__key) << std::endl;
}

